/* Copyright (c) 2016-2020 Enfry Ltd. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Enfry. 
 * You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with Enfry.
 */
package com.enfry.storage.core.pool;

import java.io.File;
import java.io.IOException;

import org.apache.commons.pool.BasePoolableObjectFactory;
import org.apache.commons.pool.PoolableObjectFactory;
import org.apache.commons.pool.impl.GenericObjectPool.Config;

import com.enfry.storage.core.ClientGlobal;
import com.enfry.storage.core.ProtoCommon;
import com.enfry.storage.core.StorageServer;
import com.enfry.storage.core.TrackerClient;
import com.enfry.storage.core.TrackerServer;
import com.enfry.storage.core.pool.StorageClient;
import com.enfry.storage.core.pool.PoolAdapter;

/**
 * 连接池实现。
 * @Title com.enfry.storage.core.pool.FastdfsPool
 * @author liulei
 * @date 2016年7月25日
 */
public class FastdfsPool extends PoolAdapter {
    private static String confPath = "fdfs_client.conf";

    public FastdfsPool(Config poolConfig, PoolableObjectFactory factory) {
        super(poolConfig, factory);
    }

    public FastdfsPool(Config poolConfig, String confPath) {
        super(poolConfig, new FastdfsClientFactory());
        this.confPath = confPath;
    }

    private static class FastdfsClientFactory extends BasePoolableObjectFactory {
        public Object makeObject() throws Exception {
            String classPath = new File(getClass().getResource("/").getFile())
                    .getCanonicalPath();
            String configFilePath = classPath + File.separator + confPath;
            ClientGlobal.init(configFilePath);
            TrackerClient tracker = new TrackerClient();
            TrackerServer trackerServer = tracker.getConnection();
            StorageServer storageServer = null;
            StorageClient client = new StorageClient(trackerServer, storageServer);
            return client;
        }

        public void destroyObject(Object obj) throws Exception {
            if ((obj != null) && ((obj instanceof StorageClient))) {
                StorageClient storageClient = (StorageClient) obj;
                TrackerServer trackerServer = storageClient.getTrackerServer();
                StorageServer storageServer = storageClient.getStorageServer();
                trackerServer.close();
                storageServer.close();
            }
        }

        public boolean validateObject(Object obj) {
            StorageClient storageClient = (StorageClient) obj;
            try {
                return ProtoCommon.activeTest(storageClient.trackerServer .getSocket());
            } catch (IOException e) {
                return false;
            }
        }
    }
}
